const Musers = require('../models/users')
const { httpJson, status, encryption, checkPwd } = require('../libs/utils/index')

const svgCaptcha = require('svg-captcha')

module.exports = {
  async register(req, res, next) {
    let body = req.body

    let user = await Musers.get(body.username)
    
    if(user.length > 0) return res.send(httpJson([], '用户已存在', status.error))

    let enPwd = encryption(body.password)
    delete body.password
    
    let result = await Musers.add({...body, ...enPwd})

    return res.send(httpJson(result))

  },
  async login(req, res, next) {
    let body = req.body

    let user = await Musers.get(body.username)
    if(user.length <= 0) {
      return res.send(httpJson([], '账号密码有误', status.error))
    }
    user = user[0]

    if(!checkPwd(user.password, user.salt, body.password)) {
      return res.send(httpJson([], '账号密码有误', status.error))
    }

    delete user.password
    delete user.salt

    res.send(user)
  },
  captcha(req, res, next) {
    let codeConfig = {
      size: 5,// 验证码长度
      ignoreChars: '0o1li', // 验证码字符中排除 0o1li
      noise: 2, // 干扰线条的数量
      color: true
    }
    let captcha = svgCaptcha.create(codeConfig);
    req.session.captcha = captcha.text.toLowerCase(); //存session用于验证接口获取文字码
    
    res.type('svg')
    res.status(200).send(captcha.data)
  }
}
